package com.alm.web.controller.alm.devbaseinfo;


import com.alm.common.annotation.Log;
import com.alm.common.core.domain.AjaxResult;
import com.alm.common.core.page.TableDataInfo;
import com.alm.common.enums.BusinessType;
import com.alm.common.utils.SecurityUtils;
import com.alm.common.utils.StringUtils;
import com.alm.handle.core.domain.entity.*;
import com.alm.handle.core.domain.entity.rq.EditIsTopRQ;
import com.alm.handle.core.domain.entity.rq.SendDevMeterRq;
import com.alm.handle.core.domain.entity.rq.SysDevCurrentDataRq;
import com.alm.handle.core.domain.entity.rq.SysDevModelRq;
import com.alm.handle.core.domain.entity.rs.HomePageCountData;
import com.alm.handle.core.domain.entity.rs.SysDevCurrentDataRS;
import com.alm.handle.service.*;
import com.alm.common.core.controller.BaseController;
import com.alm.handle.util.DevMonitorUtils;
import com.alm.handle.util.SendDataSpliceUtil;
import com.alm.handle.util.SendMessage;
import com.alm.util.ByteUtils;
import com.alm.util.InstructionByteUtils;
import com.alm.util.Misc;
import io.netty.buffer.ByteBuf;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 设备信息
 *
 * @author AIQ
 */
@RestController
@RequestMapping("/alm/dev")
public class AlmDevInfoController extends BaseController {
    @Autowired
    private ISysDevCurrentDataService sysDevCurrentDataService;
    @Autowired
    private ISysDevCommandService sysDevCommandService;
    @Autowired
    private ISysDevInfoService sysDevInfoService;
    @Autowired
    private ISysDevParamService sysDevParamService;
    @Autowired
    private ISysDevModelService sysDevModelService;
    @Autowired
    private ISysDevTypeService sysDevTypeService;
    @Autowired
    private HomePageService homePageService;

    @PreAuthorize("@ss.hasRole('common')")
    @GetMapping("/list")
    public TableDataInfo list(SysDevCurrentDataRq sysDevCurrentData) {
        sysDevCurrentData.setCommpayId(SecurityUtils.getDeptId());
        sysDevCurrentData.setIsAdmin(SecurityUtils.isAdmin(SecurityUtils.getUserId()));
        List<SysDevCurrentDataRS> list = sysDevCurrentDataService.findListByrq(sysDevCurrentData);
        return getDataTable(list);
    }

    //    @PreAuthorize("@ss.hasPermi('alm:dev:getDevCommands')")
    @PreAuthorize("@ss.hasRole('common')")
    @PostMapping("/getDevCommands")
    public AjaxResult getDevCommands(@NotNull(message = "设备mac不能为空") String deviceId) {
        SysDevInfo devInfo = sysDevInfoService.getDeviceInfo(deviceId);
        if (devInfo == null) {
            return error("设备不存在！");
        }
        SysDevCurrentData currentData = sysDevCurrentDataService.findByMac(deviceId);
        List<SysDevCommand> list = sysDevCommandService.findListAll(devInfo.getDevType(), currentData.getLineNum());
        return success(list);
    }


    @PreAuthorize("@ss.hasRole('common')")
    @PostMapping("/sendDevMeterCommand")
    public AjaxResult sendDevMeterCommand(@RequestBody SendDevMeterRq params) {
        SysDevInfo devInfo = sysDevInfoService.getDeviceInfo(params.getDeviceId());
        if (devInfo == null) {
            return error("设备不存在！");
        }
        SysDevCurrentData currentData = sysDevCurrentDataService.findByMac(params.getDeviceId());
        // 设备id
        if (currentData == null) {
            return error("设备不存在！");
        }
        SysDevCommand sysDevCommand = sysDevCommandService.findByid(params.getCmdId());
        if (sysDevCommand == null || sysDevCommand.getByteData() == null || sysDevCommand.getByteData().equals("")) {
            return error("指令不存在！");
        }
        String data = sysDevCommand.getByteData().replace("A1A1A1A1A1A1", params.getDeviceId());
        data = data.replace("A2", String.format("%02x", devInfo.getDevType()));
        boolean bo = SendMessage.sendMessage(ByteUtils.hexStrToBytes(data), devInfo.getDeviceId());
        if (bo) {
            return success(true);
        } else {
            return error("发送失败");
        }
    }

    @PreAuthorize("@ss.hasRole('common')")
    @PostMapping("/sendLineCommand")
    public AjaxResult sendLineCommand(@RequestBody SendDevMeterRq params) {
        SysDevInfo devInfo = sysDevInfoService.getDeviceInfo(params.getDeviceId());
        if (devInfo == null) {
            return error("设备不存在！");
        }
        Integer cmdId = params.getCmdId();
        List<Integer> lineNumList = params.getLineIdList();
        if (lineNumList == null || lineNumList.size() == 0) {
            return error("请选择行数");
        }
        byte[] data = SendDataSpliceUtil.multSpliceData(lineNumList, cmdId.toString());
        byte[] befor = InstructionByteUtils.getBFBYTEInstruction(devInfo.getDeviceId(),
                devInfo.getDevType());
        byte[] after = InstructionByteUtils.getBYTEISData(0x5743, devInfo.getDevType(),
                0x91,
                data, 0x008A);
        byte[] inBytes = InstructionByteUtils.getBYTEISBYTES(befor, after);
        boolean bo = SendMessage.sendMessage(inBytes, devInfo.getDeviceId());
        if (bo) {
            return success();
        } else {
            return error("发送失败");
        }
    }

    @PreAuthorize("@ss.hasRole('common')")
    @PostMapping("/getDevMonitorParams")
    public AjaxResult getDevMonitorParams(Integer paramType) {
        return success(sysDevParamService.selectDevParamTypeList(paramType));
    }


    @PreAuthorize("@ss.hasRole('common')")
    @PutMapping("/setDevMonitorParams")
    public AjaxResult setDevMonitorParams(@Validated @RequestBody SysDevMonitorParams params) {
        SysDevInfo devInfo = sysDevInfoService.getDeviceInfo(params.getDeviceId());
        if (devInfo == null) {
            return error("设备不存在！");
        }
        SysDevCurrentData currentData = sysDevCurrentDataService.findByMac(params.getDeviceId());
        // 设备id
        if (currentData == null) {
            return error("设备不存在！");
        }
        final String deviceId = params.getDeviceId();
        final byte[] data = DevMonitorUtils.convert(params.getUserInputValueList());
        byte[] befor = InstructionByteUtils.getBFBYTEInstruction(deviceId,
                devInfo.getDevType());
        byte[] after = InstructionByteUtils.getBYTEISData(0x5743, devInfo.getDevType(),
                0x91,
                data, 0x008A);
        byte[] inBytes = InstructionByteUtils.getBYTEISBYTES(befor, after);
        boolean bo = SendMessage.sendMessage(inBytes, devInfo.getDeviceId());
        if (bo) {
            return success();
        } else {
            return error("发送失败");
        }
    }

    @PreAuthorize("@ss.hasRole('common')")
    @GetMapping("/getDevModelList")
    public TableDataInfo getDevModelList(SysDevModel sysDevModel) {
        startPage();
        List<SysDevModel> sysDevModelList = sysDevModelService.selectModelList(sysDevModel);
        return getDataTable(sysDevModelList);
    }

    @PreAuthorize("@ss.hasRole('common')")
    @PutMapping("/editDevModelInfo")
    public AjaxResult editDevModelInfo(@Validated @RequestBody SysDevModel sysDevModel) {
        int count = sysDevModelService.updateDevModelInfo(sysDevModel);
        return success(count);
    }

    @PreAuthorize("@ss.hasRole('common')")
    @DeleteMapping("/delDevModelInfo/{modelId}")
    public AjaxResult delDevModelInfo(@PathVariable("modelId") Long modelId) {
        int count = sysDevModelService.delDevModelInfo(modelId);
        return success(count);
    }

    @PreAuthorize("@ss.hasRole('common')")
    @PutMapping("/addDevModel")
    public AjaxResult addDevModel(@Validated @RequestBody SysDevModel sysDevModel) {
        if (sysDevModel.getType().length() > 9) {
            return error("长度太长！");
        }
        int count = sysDevModelService.addDevModel(sysDevModel);
        return success(count);
    }

    @PreAuthorize("@ss.hasRole('common')")
    @GetMapping("/getDevModelType")
    public AjaxResult getDevModelType() {
        List<SysDevType> sysDevTypeList = sysDevTypeService.getDevModelType();
        return success(sysDevTypeList);
    }

    @PreAuthorize("@ss.hasRole('common')")
    @GetMapping("/querHomePage")
    public AjaxResult querHomePage() {
        HomePageCountData data = homePageService.countHomePageData();
        return success(data);
    }

    /**
     * 是否置顶
     * @return
     */
    @PreAuthorize("@ss.hasRole('common')")
    @PostMapping("/editIsTop")
    public AjaxResult editIsTop(@RequestBody EditIsTopRQ rq) {
        int row = sysDevInfoService.editIsTop(rq);
        return success();
    }
}
